var userId = guid();
var name = getUserName();
var onlineUserMap = new Map();
var lottoryMap = new Map();
var socket;

var progress;


function onHtmlLoad() {
    name = getUserName();
    userId = guid();
    $("#name").val(name);
    progress = document.getElementById("progring");
}


function channelOpen(event) {
    console.log("channelOpen");
    console.log(event);
    console.log("send login cmd");
    sendMessage(loginCmd());
}

function channelRead(event) {


    let resp = JSON.parse(event.data);

    // console.log("channelRead.收到服务器消息:" + resp);
    // console.log("channelRead.收到服务器消息-end-----------------------");

    switch (resp.actionId) {
        case 20002: //登录
            onlineUserMap.set(resp.userId, resp);
            freshOnlineUserList();
            break;
        case 20003: //获取列表
            onlineUserList(resp.itemList);
            break;
        case 20004:
            userId = resp.userId;
            name = resp.userName;
            break;
        case 21001: //退出登录
            onlineUserMap.delete(resp.userId);
            freshOnlineUserList();
            break;
        case 21002: //退出登录列表
            onlineUserList(resp.itemList);
            break;
        case 40002:     //收到是谁开始抽奖的
            console.log(resp.data);
            break;
        case 41002:     //添加抽奖用户成功
            const addData = resp.data;
            lottoryMap.set(addData.uuid, addData);
            freshLottoryUserList();
            break;
        case 41003: //添加抽奖用户失败
            console.log(resp);
            break;
        case 42002: //移除抽奖用户成功
            lottoryMap.delete(resp.data.uuid);
            freshLottoryUserList();
            break;
        case 42003: //移除抽奖用户失败
            console.log(resp);
            break;
        case 43000: //获取抽奖列表
            console.log('获取抽奖列表');
            console.log(resp);
            lottoryUserList(resp.itemList);
            break;
        case 43001: //抽奖进度
            let pd = resp.data;
            progress.innerHTML = pd.userName;
            break;
        case 43002: //没人抽奖
            handlerNoPeopleJoin(resp);
            break;

        case 44444:  //幸运用户
            console.log("幸运用户");
            console.log(resp);
            handlerLoculyUser(resp);
            break;


    }

}

function onlineUserList(list) {
    onlineUserMap.clear();
    for (let i = 0; i < list.length; i++) {
        let temp = list[i];
        onlineUserMap.set(temp.userId, temp);
    }
    freshOnlineUserList();
}

function lottoryUserList(list) {
    lottoryMap.clear();
    for (let i = 0; i < list.length; i++) {
        let temp = list[i];
        lottoryMap.set(temp.uuid, temp);
    }
    freshLottoryUserList();
}


function channelClose(event) {
    console.log("channelClose");
    console.log(event);
}

function exceptionCatch(event) {
    console.log("exceptionCatch");
    console.log(event);
}

function connServerClick() {
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    if (window.WebSocket) {
        socket = new WebSocket($("#ip").val()); //建立连接,并发送信息
        socket.onopen = channelOpen;
        socket.onmessage = channelRead;
        socket.onclose = channelClose;
        socket.onerror = exceptionCatch;

    } else {
        alert("浏览器不支持WebSocket!");
    }

}

function disConnServerClick() {
    console.log("disConnServerClick");
    socket.close();
}

function changeUserName() {
    name = getUserName();
    userId = guid();
    $("#name").val(name);
}


function loginCmd() {
    var time = Date.parse(new Date()) / 1000;

    return JSON.stringify({
        "userId": userId,
        "userName": name,
        "actionId": 20001,
        "time": time
    });
}


function loginCmdClick() {
    sendMessage(loginCmd());
}


function sendDataClick() {
    console.log("send data");

    var data = JSON.stringify({
        "userId": userId,
        "userName": name,
        "actionId": 1001
    });
    sendMessage(data);
}

function sendMessage(message) {
    if (!window.WebSocket) {
        return;
    }
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(message);
    } else {
        console.log("WebSocket连接没有建立成功!");
        alert("您还未连接上服务器，请刷新页面重试");
    }
}


// 刷新上线人员
function freshOnlineUserList() {
    $("#showOnlineNames").empty();

    var index = 0;
    for (var [key, item] of onlineUserMap.entries()) {
        // console.log(key);
        // console.log(item);
        // console.log("-----------------------------------------");
        $("#showOnlineNames").append('<tr><td>' + (++index) + '</td>' +
            '<td>' + item.userName + '</td>' +
            '</tr>');
    }
}

// 刷新上线人员
function freshLottoryUserList() {

    console.log(lottoryMap.length);

    $("#showLottory").empty();

    var index = 0;
    for (var [key, item] of lottoryMap.entries()) {
        console.log(key);
        console.log(item);
        console.log("-----------------------------------------");
        $("#showLottory").append('<tr><td>' + (++index) + '</td>' +
            '<td>' + item.userName + '</td>' +
            '</tr>');
    }
}


function addMineToLottory() {
    const time = Date.parse(new Date()) / 1000;
    const lottory = JSON.stringify({
        "actionId": 41000,
        "userId": userId,
        "userName": name,
        "time": time,
        "data": name
    });
    sendMessage(lottory);
}


function addUserToLottory() {

    let lottoryName = document.getElementById('lottoryName').value;
    if (lottoryName.trim() === '') {
        return;
    }
    const time = Date.parse(new Date()) / 1000;
    const lottory = JSON.stringify({
        "actionId": 41001,
        "userId": userId,
        "userName": name,
        "time": time,
        "data": lottoryName
    });
    sendMessage(lottory);
}

function removeMineFromLottory() {
    const time = Date.parse(new Date()) / 1000;
    const lottory = JSON.stringify({
        "actionId": 42000,
        "userId": userId,
        "userName": name,
        "time": time,
        "data": userId
    });
    sendMessage(lottory);
}

function lottoryList() {
    const time = Date.parse(new Date()) / 1000;
    const lottory = JSON.stringify({
        "actionId": 43000,
        "userId": userId,
        "userName": name,
        "time": time
    });
    sendMessage(lottory);
}

function startLottory() {
    const time = Date.parse(new Date()) / 1000;
    const lottory = JSON.stringify({
        "actionId": 40000,
        "userId": userId,
        "userName": name,
        "time": time
    });
    sendMessage(lottory);
}

function stopLottory() {
    const time = Date.parse(new Date()) / 1000;
    const lottory = JSON.stringify({
        "actionId": 40001,
        "userId": userId,
        "userName": name,
        "time": time
    });
    sendMessage(lottory);
}


function handlerNoPeopleJoin(bean) {
    alert("没有参加,你转什么转?");
}

function handlerLoculyUser(bean) {

    console.log(bean);

    var s = "抽奖人:" + bean.userName + ".抽奖人ID=" + bean.userId;
    s += "<br/>";
    var data = bean.data;

    s += "幸运用户是=[" + data.userName + "].ID=[" + data.uuid + "]";
    document.getElementById("locklyUser").innerHTML = s;
    if (data.uuid === userId) {
        alert("你就是那个幸运儿!");
    }
}